<template>
  <div >
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>


    <div style="height: 400px">
      <!-- 项目进度图标 -->
      <div style="position: absolute; left: 50px;">
        <div slot="header" style="height: 30px;text-align: center;" class="clearfix">
          <span style="font-size:20px; display: inline-block; font-weight: bold;" > 开发中项目进度展示 </span>
        </div>
        <!-- 2.为Echarts准备一个具备大小（宽高）的dom -->
        <div id="projectProcessChart" style="width: 600px; height: 350px;"></div>
      </div>

      <!-- 知识点散布图 -->
      <div style="position: relative; left: 800px;">
        <div slot="header" style="height: 30px;padding-left: 200px;" class="clearfix">
          <span style="font-size:20px; display: inline-block; font-weight: bold;" > 项目知识点散布展示 </span>
        </div>
        <!-- 2.为Echarts准备一个具备大小（宽高）的dom -->
        <div id="knowChart" style="width: 600px; height: 350px;"></div>
      </div>
    </div>
    <el-divider></el-divider>


    <!-- 个人信息 -->
    <!--项目展示-->
    <div>
      <el-card class="box-card" style="width: 80%; height:200px; margin: 0 20px;" >
        <div slot="header" style="height: 30px" class="clearfix">
          <span style="font-size:20px; display: inline-block; font-weight: bold;" > 我参与的项目 </span>
        </div>

        <el-table
                height="120px"
                :show-header="false"
                v-loading="projectInfo.listLoading"
                :data="projectInfo.list"
                element-loading-text="Loading"
                fit
                highlight-current-row>
          <el-table-column label="" width="80" align="center">
            <template scope="scope">
              <span>{{ scope.$index + 1 }} </span>
            </template>
          </el-table-column>
          <el-table-column prop="proName" label="项目名称" width="150" align="center">
            <template slot-scope="scope">
              <el-button type="text"
                         content="查看详情"
                         @click="projectDetail(scope.row.id)"
              >{{scope.row.proName}}</el-button>
            </template>
          </el-table-column>

          <el-table-column prop="proDescribe" label="项目简介" width="250" align="center"/>
          <el-table-column prop="teamName" label="项目组" width="150" align="center"/>
          <el-table-column prop="userArr" label="成员" width="250" align="center"/>
          <el-table-column prop="process" label="项目进度" width="80" align="center">
            <template slot-scope="scope">{{scope.row.process}}%</template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>
<script>
  //1.导入echarts
  import * as echarts from 'echarts'
  export default {
    data() {
      return {
        projectInfo:{
          list: [],
          listLoading: true}
      }
    },

    mounted() {
      this.initInfo();
      this.messageCount = 1;
      this.processChart();
      this.knowChart()
    },

    methods: {
      initInfo() {
        if (!localStorage.getItem("jwt")) {
          this.$router.replace('/login')
        }
        let url = 'http://localhost:8989/projects/projectListByUserId';
        console.log('url = ' + url);
        this.projectInfo.listLoading = true;
        this.axios
                .create({'headers': {'Authorization': localStorage.getItem("jwt")}})
                .get(url).then((response) => {
          let responseBody = response.data;
          this.projectInfo.list = responseBody.data;
          this.projectInfo.listLoading = false;
        })
      },
      /* 详情 */
      projectDetail(id) {
        this.$router.push({path: '/projects/detail', query: {id}})
      },

      //项目进度图标数据填充
      processChart(){

        const projectProcessChartDatas = [];
        //获取图标数据
        console.log('loadProjectList');
        let url = 'http://localhost:8989/projects/projectForChartArray';
        console.log('url = ' + url);
        this.axios
                .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
                .get(url).then((response) => {
          let responseBody = response.data;
          if(responseBody.state==20000){
            let projectProcessChartList = responseBody.data;
            projectProcessChartList.forEach(function (projectProcessChartData) {
              projectProcessChartDatas.push([projectProcessChartData.process,projectProcessChartData.proName]);
            })
            this.initProjectProcessChart(projectProcessChartDatas)
            console.log("图标数据all:"+projectProcessChartDatas);
          }else {
            this.$message.error("项目进度信息获取失败");
          }
        })
      },
      //项目进度图标初始化
      initProjectProcessChart(projectProcessChartDatas){
        let chartDom = document.getElementById('projectProcessChart');
        let myChart = echarts.init(chartDom);

        //let projectProcessData =
        myChart.setOption({
          //      title: { text: '开发中项目进度展示' },
          dataset:{
            source:projectProcessChartDatas
          },
          grid: { containLabel: true },
          xAxis: {
            name: '进度',
            type: 'value',
            min: 0,
            max: 100,
            //data:[0,10,20,30,40,50,60,70,80,90,100],
            axisLabel: {
              formatter: '{value} %'
            }
          },
          yAxis: {
            name: '项目',
            type: 'category'

          },
          visualMap: {
            orient: 'horizontal',
            left: 'center',
            min: 10,
            max: 100,
            text: ['High Score', 'Low Score'],
            // Map the score column to color
            dimension: 0,
            inRange: {
              color: ['#CD5C5C', '#FFCE34', '#006400']
            }
          },
          series: [
            {
              type: 'bar',
              encode: {
                // Map the "amount" column to X axis.
                x: 'process',
                // Map the "product" column to Y axis
                y: 'proName'
              }
            }
          ]
        });

        //option && myChart.setOption(option);
      },

      //知识点散布图数据填充
      knowChart(){
        //获取图标数据
        let url = 'http://localhost:8989/projects/projectKnows';
        const projectKnowProNames = [];
        const projectKnowInfos = [];
        console.log('url = ' + url);
        this.axios
                .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
                .get(url).then((response) => {
          let responseBody = response.data;
          if(responseBody.state==20000){
            let projectKnowList = responseBody.data;
              projectKnowList.forEach(function (projectKnowChartData,idx) {
                projectKnowProNames.push(projectKnowChartData.proName);
                projectKnowInfos.push([idx,projectKnowChartData.projectKnowsCreateTimes]);
                //let knowsInfo = ;
                console.log("数据:"+projectKnowInfos);
                //this.test(idx,projectKnowInfos);
            })
            this.initKnowChart(projectKnowProNames,projectKnowInfos)
            console.log("图标数据all:"+projectKnowInfos);
          }else {
            this.$message.error("项目进度信息获取失败");
          }
        })
      },

      //知识点散布图初始化
      initKnowChart(proNames,projectKnowInfos){
        const knowData = [];
        let date = new Date();
        let proNamesSize = proNames.length;
        projectKnowInfos.forEach(function (projectKnowChartData,idx) {
          let number = projectKnowChartData[0];
            console.log("idx:"+idx);
            let knows = projectKnowChartData[1];
          let newKnows = knows.split(',');
          console.log("knows:"+newKnows);
          console.log("length:"+newKnows[2]);
            for(let i = 1; i<newKnows.length;i++){
              console.log("projectKnowChartData:"+projectKnowChartData);
              console.log("projectKnowChartData[i]:"+projectKnowChartData[1][i]);
              let date1 = new Date(newKnows[i].substring(0,10))
              let num = (date.getTime()-date1.getTime())/(24*60*60*1000)
              knowData.push([number,Math.round(num),Math.random()*10]);
            }
          console.log("11111:"+projectKnowChartData);
        })
        console.log("data11111:"+knowData);

        let chartDom = document.getElementById('knowChart');
        let myChart = echarts.init(chartDom);
        let option;
        let list = this.getDateRange(date, 30, true);
        console.log(list, '最后得到的日期数组')
        const xDays = this.getDateRange(date, 30, true);
        const title = [];
        const singleAxis = [];
        const series = [];
        proNames.forEach(function (proName, idx) {
          title.push({
            textBaseline: 'middle',
            top: ((idx + 0.5) * 100) / proNamesSize + '%',
            text: proName,
            textStyle: {
              fontSize:14,
              fontWeight:'normal'
            }
          });
          let insideValue = true;
          //if(idx==0){
          // insideValue = true;
          //}
          singleAxis.push({
            left: 150,
            type: 'category',
            boundaryGap: false,
            data: xDays,
            top: (idx * 100) / proNamesSize + 5 + '%',
            height: 100 / proNamesSize - 10 + '%',
            axisLabel: {
              inside: insideValue,
              interval: 2
            },
            axisTick:{
              show:true,
              inside:false,
            },
            splitLine:{
              show: false
            }
          });
          series.push({
            singleAxisIndex: idx,
            coordinateSystem: 'singleAxis',
            type: 'scatter',
            data: [],
            symbolSize: function (dataItem) {
              return dataItem[1] * 4;
            }
          });
        });
        knowData.forEach(function (dataItem) {
          series[dataItem[0]].data.push([dataItem[1], dataItem[2]]);
        });
        option = {
          //   title: { text: '开发中项目进度展示' },
          tooltip: {
            position: 'bottom'
          },
          title: title,
          singleAxis: singleAxis,
          series: series
        };

        option && myChart.setOption(option);
      },
      //时间数组
      getDateRange(dateNow,intervalDays,bolPastTime){
        let oneDayTime = 24 * 60 * 60 * 1000;
        let list = [];
        let lastDay;

        if(bolPastTime == true){
          for(let i = 0; i<intervalDays; i++){
            lastDay = this.formateDate(new Date(dateNow.getTime() - i * oneDayTime));
            let day = lastDay+"";
            list.push(day.substring(5,10));
          }
        }else{
          for(let i = 0; i<intervalDays; i++){
            lastDay = new Date(dateNow.getTime() - 2 * oneDayTime);
            console.log(lastDay);
            list.push(this.formateDate(lastDay));
          }
        }
        return list;
      },
      formateDate(time){
        let year = time.getFullYear()
        let month = time.getMonth() + 1
        let day = time.getDate()

        if (month < 10) {
          month = '0' + month
        }

        if (day < 10) {
          day = '0' + day
        }
        return year + '-' + month + '-' + day + ''
      }
    }
  }
</script>